<?php

!defined('IN_SYSTEM') && exit('Access denied');

class orderControlPage extends commonControlPage {

    /**
     * 获取订单详情
     */
    public function getdescModule() {
        if (AJAX) {
            $id = $_POST['osn'];
            $rows = $_ENV['db']->fetchAll("SELECT o.*,p.code,pi.hash,p.num,pi.filepath,pi.ext FROM `order_detail` as o LEFT JOIN `product` as p ON o.product_id=p.product_id  LEFT JOIN product_image as pi ON p.default_imagehash=pi.hash WHERE o.`order_sn` = '{$id}'");

            $html = '<table class="order_fast_view">';
            $html .= '<tr><th>商品名称</th><th>货号</th><th>数量</th><th>库存</th><th>单价</th><th>小计</th></tr>';
            if (empty($rows)) {
                $html .= '<tr><td colspan="4">未关联任何商品</td></tr>';
            } else {
                foreach ($rows as $p) {
                    $html .= "<tr><td>".($p['hash'] ? '<img src="./attach/'.$p['filepath'].'/'.$p['hash'].'_small.'.$p['ext'].'"/>' : '没有图片')."<br/>{$p['product_name']}</td><td>{$p['code']}</td><td>{$p['product_num']}</td><td>{$p['num']}</td><td>{$p['product_pprice']}</td><td>{$p['product_total_pprice']}</td></tr>";
                }
            }
            $order_history = $_ENV['db']->fetchAll("SELECT * FROM order_history where order_sn = '{$id}'");            
            $html .= "<tr><td colspan='6'>";
            foreach ((array)$order_history as $item) {
                $html .= "{$item['username']},{$item['desc']},".date('Y-m-d H:i:s',$item['timestamp']).'<br/>';
            }
            $html .= '</td></tr></table>';

            $this->outputJson(1,$html);
        } else {
            $this->outputJson(0,'ERROR');
        }
    }

    /**
     * 订单列表
     */
    public function listModule() 
	{
		$where = ' where 1 ';
		
		$rowset = $_ENV['db']->fetch(" select count(o.order_id) as `total`  from `order` o left join `tuihuom` t on  o.order_id = t.order_id ");
        $total = $rowset['total'];
        unset($rowset);
        $pager = new class_pager();
        $pager->setConfig((int)$_GET['page_no'],$total);
        $_GET['page_no'] = 'TPT';
        $pager->setUrl("?".http_build_query($_GET),'TPT');
        $this->view->pager = $pager->output();
        $this->view->orders = $_ENV['db']->fetchAll(" select t.tid as tid,t.pprice as tprice,t.audit_state as tstate,o.*  from `order` o left join `tuihuom` t on  o.order_id = t.order_id {$where} {$order} LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
   
        $this->showMainPage('admincp/order/order_list');
    }



    /**
     * 订单审核
     */
	private function checkOrderProductNum($oid) {
		$count = $_ENV['db']->fetchCol("SELECT count(1) FROM `order_detail` as d LEFT JOIN `product` as p ON d.product_id=p.product_id WHERE d.order_id = '{$oid}' AND d.product_num > p.num");
		return $count;
	}
    public function __call($func,$arg) 
    {
        $this->view->addScript('rili');
        $step = substr($func,0,-6);# 当前页面的操作名称
        if (in_array($step,array('fenpei','yewuyuan','caiwu','shenpi','kucun'))) 
		{
		
            // 初始化系统级变量
            $node_id = $_ENV['config']['order_audit_nodes'][$step];
            $oas = $_ENV['config']['order_audit_state'][$step];
			

			
            if ('view' == $_GET['opt']) 
			{
                $order_id = (int)$_GET['oid'];
                $order = orderEntity::GetRow($order_id);
                if (!$order) $this->showMessage('订单不存在','back');

                #########################  操作部分开始  #########################
                if (POST && AJAX) 
				{
                    $type = $_POST['type'];
                    $mark = htmlspecialchars($_POST['mark']);
                    // node_id
                    $node_id = $_ENV['config']['order_audit_nodes'][$type];

                    if ($order['audit_state'] == 100) 
                    {
                        $this->outputJson(0,'操作失败，该订单已被作废');
                    }

                    # 权限判定
                    if (($this->user['uid']!=$order['co_member_id'] && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) || ($step != 'caiwu' ? $order['audit_state'] != $oas : !in_array($order['audit_state'],array(2,3,4,5)))) 
                    {
                        $this->outputJson(0,'非法操作');
                    }
                    
                    // 除了订单分配，每步操作都验证订单确认状态
                    if (!in_array($type,array('queren','yewuyuan'))) 
                    {                        
                        if (!$order['pc'] || !$order['pprice']) 
                        {
                            $this->outputJson(0,'请先确认订单');
                        }
                    }


                    $curopt = strtr($step,array(
                        '0' => '分配',
                        '1' => '确认订单',
                        '2' => '审批',
                        '3' => '出库',
                        '4' => '采购',
                        '5' => '已出库',
                    ));

                    $next_uid = (int)$_POST['next_uid'];
                    $param = array();
                    $param['co_member_id'] = $next_uid;
                    $param['last_time'] = $_ENV['time'];
                    
                    $name = $this->user['username'];

                    switch($type) 
                    {
                        case 'yewuyuan':
                            $param['audit1_uid'] = $this->user['uid'];
                            $param['audit1_name'] = $name;
                            $param['audit_state'] = '1';          //状态：待确认
                        break;

                        case 'queren':
                            switch($_POST['opt']) 
							{
                                case 'price':  //商品价格保存
                                    $pprice = array_filter($_POST['pprice']);
                                    // 获取该订单的所有商品列表
									$products = orderEntity::GetOrderDetail($order_id);
                                    $sql_tmp = array();
                                    $all_price = 0;
                                    foreach ($products as $product) 
									{
                                        if (!$pprice[$product['product_id']]) 
										{
                                            $this->outputJson(0,'请填写全部的实际售价信息');
                                        }
                                        $tmp_price = $product['product_num']*$pprice[$product['product_id']];
                                        $all_price+=$tmp_price;

                                        $sql_tmp[] = "UPDATE order_detail ".$this->buildSql(array(
                                                'product_pprice' => $pprice[$product['product_id']],
                                                'product_total_pprice' => $tmp_price,
                                            ))." WHERE order_id = '{$order['order_id']}' AND product_id = '{$product['product_id']}'";
                                    }
                                    $sql_tmp[] = "UPDATE `order` ".$this->buildSql(array(
                                            'pprice' => $all_price,
                                            'last_time' => time(),
                                        ))." WHERE `order_id` = '{$order['order_id']}'";
                                    foreach ($sql_tmp as $sql) 
									{
                                        $_ENV['db']->runSql($sql);
                                    }
                                    $this->addOrderHistory($order['order_sn'],"确认了订单销售信息");
                                    $this->outputJson(1,"操作成功");
                                break;

                                case 'hetong':
                                    # 获取合同类型
                                    $contract_list = explode("\n",$_ENV['config']['contract']);
                                    # 验证银行信息
                                    $bank_name = $_POST['bank_name'];
                                    $bank_no = $_POST['bank_no'];
                                    if (!in_array($bank_name,explode("\n",$_ENV['config']['bank_list']))) {
                                        $this->outputJson(0,'请选择客户付款的银行');
                                    }
                                    if (strlen($bank_no) != 19 OR !preg_match('/\d+/',$bank_no)) {
                                        $this->outputJson(0,'银行帐号应该为19个数字组成的');
                                    }
                                    
                                    # 验证合同类型是否合法
                                    $contract = $_POST['contract'];
                                    if (!$contract || !in_array($contract,$contract_list)) $this->outputJson(0,'请选择正确的合同类型');
                                    $contract_number = $_POST['contract_number'];
                                    if (!$contract_number || mb_strlen($contract_number,'UTF-8') > 20) $this->outputJson(0,'合同号错误');

                                    $pc = $_POST['price_content'];// price_content
                                    if (!$pc || count($pc) != 3) $this->outputJson(0,'请填写全部信息');
                                    foreach ((array)$pc as $no=>$item) {
                                        $nt = strtr($no,array(1=>'预付款',2=>'收货后付款',3=>'尾款'));
                                        if (!preg_match('/^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/',$item['time'])) {
                                            $pc[$no]['time'] = strtotime($item['time']);
                                            $this->outputJson(0,"{$nt}付款时间格式错误");
                                        }
                                        if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$item['price'])) {
                                            $this->outputJson(0,"{$nt}付款金额格式错误");
                                        }
                                        if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$item['percent'])) {
                                            $this->outputJson(0,"{$nt}付款百分比格式错误（请勿填入百分号）");
                                        }
                                    }

                                    $pc = json_encode($pc);
                                    $_ENV['db']->runSql("UPDATE `order` ".$this->buildSql(array(
                                            'pc' => $pc,
                                            'contract' => $contract,
                                            'contract_number' => $contract_number,
                                            'bank_name' => $bank_name,
                                            'bank_no' => $bank_no
                                        ))." WHERE order_id = '{$order_id}'");
                                    $this->addOrderHistory($order['order_sn'],"确认了订单合同信息");
                                    $this->outputJson(1,'操作成功');
                                break;

                                default:
                                    $this->outputJson(0,'异常_E3');
                                break;
                            }
                            $this->outputJson(0,'异常_E1');
                        break;

                        case 'shenpi':
                            // 查询当前用户是否已经参与过审批
                            if (orderEntity::IsShenPi($this->user['uid'],$order_id)) {
                                $this->outputJson(1,'您已经审批过该订单');
                            }
                            $param['audit_state'] = '2';
                            // 更新审批次数
                            $_ENV['db']->runSql("update `order` set audit_total=audit_total+1 where order_id = '{$order_id}'");
                            // 增加审批记录
                            $_ENV['db']->runSql("INSERT INTO order_audit_history ".$this->buildSql(array(
                                    'order_id' => $order_id,
                                    'uid' => $this->user['uid'],
                                )));
                        break;

                        case 'jiakuan':
                            if ($step!='caiwu') $this->outputJson(0,'操作失败');
                            $price = $_POST['price'];
                            $confirm_price = $_POST['confirm_price'];
                            
                            if (!$mark) {
                                $this->outputJson(0,'请填写备注信息');
                            }
                            if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$price) || !preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$confirm_price)) {
                                $this->outputJson(0,'请核对您的金额');
                            }
                            if ($price <= 0) {
                                $this->outputJson(0,'金额不能为0');
                            }
                            if ($price != $confirm_price) {
                                $this->outputJson(0,'两次输入金额不一致');
                            }
                            
                            // 订单加款逻辑判断处理
                            $payed = $order['payed'] + $price;
                            if ($payed > $order['pprice']) {
                                $this->outputJson(0,'金额过大，请确认当前订单已付款加上您输入的款项总和不大于订单总应付款项');
                            }

                            $_ENV['db']->runSql("INSERT INTO `order_payed_history` ".$this->buildSql(array(
                                    'order_id' => $order['order_id'],
                                    'order_sn' => $order['order_sn'],
                                    'payed' => $price,
                                    'arr' => $order['pprice']-$payed,
                                    'uid' => $this->user['uid'],
                                    'username' => $this->user['username'],
                                    'mark' => $mark,
                                    'created_time' => $_ENV['time'],
                                )));
                            $jparam = array();
                            $jparam['payed'] = $payed;
                            $jparam['last_time'] = $_ENV['time'];
                            
							if ($payed==$order['pprice'] && $order['audit_state']=='5') 
							{  //当全额换完，且已出库才能更改其状态
                                $jparam['audit_state'] = '6';
                                $jparam['co_member_id'] = '0';
                            }
	
                            $_ENV['db']->runSql("UPDATE `order` ".$this->buildSql($jparam)." WHERE `order_id` = '{$order['order_id']}'");

                            $this->outputJson(1,'回款操作成功');
                        break;

                        case 'kucun':
							if ($this->checkOrderProductNum($order['order_id'])) {
								$this->outputJson(0,'当前订单有商品库存不足，无法转交库存处理');
							}
                            // 如果不是审批转库存
                            if ($step != 'shenpi') {
                                $param['audit5_uid'] = $this->user['uid'];
                                $param['audit5_name'] = $this->user['username'];
                            }
                            $param['audit_state'] = 3;
                        break;

                        case 'caigou':
							if (!$this->checkOrderProductNum($order['order_id'])) {
								$this->outputJson(0,'当前订单所有商品库存充足，无需采购');
							}
                            // 如果不是审批转采购
                            if ($step != 'shenpi') {                                
                                $param['audit3_uid'] = $next_uid;
                                $param['audit3_name'] = $name;
                            }
                            $param['audit_state'] = 6;
                        break;

                        case 'chuku':
							if ($this->checkOrderProductNum($order['order_id'])) {
								$this->outputJson(0,'当前订单有商品库存不足，无法出库.');
							}
                            $param['co_member_id'] = $order['audit1_uid'];
                            $param['audit3_uid'] = $this->user['uid'];
                            $param['audit3_name'] = $name;
                            $param['audit_state'] = 5;
                        break;

                        case 'trash':
                            $_ENV['db']->runSql('UPDATE `order` '.$this->buildSql(array(
                                    'co_member_id' => '0',
                                    'audit_state' => '100',
                                    'last_time' => $_ENV['time'],
                                )).' WHERE `order_id` = \''.$order_id.'\'');
                            $this->addOrderHistory($order['order_sn'],"{$curopt}作废该订单",$mark);
                            $this->outputJson(1,'操作成功');
                        break;

                        default:
                            $this->outputJson(0,'异常_001');
                        break;
                    }
					
                    # 验证要求的下级人员是否合法
                    if (!in_array($type,array('chuku','trash')))
					 {
						 if(class_permission::ValidateNodeByUser($node_id,$next_uid))
						 {
							  $this->outputJson(0,$step.'被指派的用户没有权限');
						 }
                         $next_user = $_ENV['db']->fetch("SELECT username,nickname FROM `admincp_member` WHERE `uid` = '{$next_uid}'");
                    }
					
                    # 订单转交给下级审核员
					UpdateTable('order',$param,array('order_id'=>$order_id));
					
                    # 出库更改
                    if ($type == 'chuku') 
					{
                        #获取订单商品ID和购买数量
                        $opin = $_ENV['db']->fetchAll("SELECT product_num,product_id FROM order_detail WHERE order_id = {$order_id}");
                        foreach ($opin as $p) {
                            $run_row = $_ENV['db']->runSql("UPDATE `product` SET `num` = `num`-{$p['product_num']},`sold_num`=sold_num+{$p['product_num']} WHERE `product_id` = '{$p['product_id']}'");
                            if (!$run_row) {
                                $this->outputJson(0,'更改库存失败');
                            }
                        }
                    }
					
                    # 记录历史
                    if ($step != 'fenpei') {
                        $this->addOrderHistory($order['order_sn'],"{$curopt}通过转交给{$next_user['username']}[{$next_user['nickname']}]进行处理",$mark);
                    } else {
                        $this->addOrderHistory($order['order_sn'],"{$curopt}通过等待业务员进行处理",$mark);
                    }
                    
                    $this->outputJson(1,'操作成功');
                }
                #!########################  操作部分结束  #########################

                #########################  订单查看页面  #########################
                $this->view->order_product_list = orderEntity::GetOrderDetails($order_id);                 //订单关联的商品列表
				$this->view->order_history =orderEntity::GetOrderHistorys($order['order_sn']);             //订单操作历史记录
                $this->view->order_payed_history = orderEntity::GetOrderPayedHistory($order['order_id']);  //订单付款记录   
             
			 
			 	/*订单类别*/
                $this->view->contract = BindCombox("contract","contract",explode("\n",$_ENV['config']['contract']),$order['contract']);
                /*银行列表*/
				$this->view->banks = BindCombox("bank_name","bank_name",explode("\n",$_ENV['config']['bank_list']),$order['bank_name']);
                 
		 
                # 获取订单下级操作人列表
                #    如果当前操作不是财务
                if ($step != 'caiwu') 
				{
                    $users_html= $this->BindCombox($step,$node_id);
                }
				
                # 当前可执行的操作
                # 允许操作：当前订单是当前登录用户有权限管理的并且超级管理员允许操作
                $this->view->operation = $this->GetOperation($order,$step,$oas);

                $this->view->step = $step;
                $this->view->order = $order;
                $this->view->cpc = @json_decode($order['pc'],1);
				
                $this->view->users_html = $users_html;
                $this->showMainPage('admincp/order/order_audit_desc_' .$step );
                #!########################  订单查看页面结束  #########################
            } 
			else 
			{
                #########################  订单列表页面  #########################
                $this->getOrderList($step,$this->user['uid']);
                $this->showMainPage('admincp/order_audit_list');
                #!########################  订单列表结束  #########################
            }
        } 
		else 
		{
            parent::__call($func,$arg,$oas);
        }
    }

	/*[绑定用户列表]*/
	private function BindCombox($step,$node_id)
	{
		$users_html = '<select name="next_users" id="next_uid">';                            
		$users =  class_permission::GetUsersByNodes($node_id);			
        foreach ((array)$users as $user) 
		{
            $users_html .= '<option value="'.$user['uid'].'">'."{$user['username']}[{$user['nickname']}]".'</option>';
        }
        $users_html .= '</select>';
		return $users_html;
	}

	private function GetOperation($order,$step,$oas)
	{
		$operation = '';
		//是否授权用户(1) 所属业务员下的单子  (2)当前用户是管理员
		$isAudUser = ($this->user['uid'] == $order['co_member_id']) || (in_array($this->user['uid'],$_ENV['config']['superadmin']));    
		
		if ($isAudUser && ($step != 'caiwu' ? $order['audit_state'] == $oas : in_array($order['audit_state'],array(2,3,4,5)))) 
		{
					switch ($step) 
					{
                        case 'fenpei':     // 分配
                            $operation = '<input type="button" rel="opt" title="yewuyuan" value="通过，转业务员操作" style="color:green" />';
                        break;
                        case 'yewuyuan':  // 业务员补充确认
                            $operation = '<input type="button" rel="opt" title="shenpi" value="通过,转订单审批" style="color:green"/>';
                        break;
                        case 'shenpi':
                            // 如果当前订单已经被当前用户操作过，就不显示按钮
                            if (!$_ENV['db']->fetchCol("SELECT count(1) FROM order_audit_history WHERE `uid` = '{$this->user['uid']}' and `order_id` = '{$order_id}'")) 
							{
                                $operation = '<input type="button" rel="opt" title="shenpi" value="通过,转订单审批" style="color:green"/>';
                            }
                            $operation .= '<input type="button" rel="opt" title="kucun" value="通过，转库存" style="color:green" />';
                            //$operation .= '<input type="button" rel="opt" title="caigou" value="库存不足，转采购" style="color:green" />';
                        break;
                        case 'kucun':
                            $operation = '<input type="button" rel="opt" title="chuku" value="通过，出库" style="color:green" />';
                           // $operation .= '<input type="button" rel="opt" title="caigou" value="库存不足，转采购" style="color:green" />';
                        break;
                        case 'caigou':
                            //$operation = '<input type="button" rel="opt" title="kucun" value="采购完成，转库存" style="color:green" />';
                        break;
                        case 'caiwu':
                            $operation = '<input type="button" rel="opt" title="jiakuan" value="提交" style="color:green" />';
                        break;
                    }

		}
		return  $operation;
	}

	/**
	 * 订单采购
	 */
	public function stockModule() {

		// 商品入库页面
		if (is_numeric($_GET['product_id'])) {
			$product = $_ENV['db']->fetch("SELECT * FROM `product` WHERE `product_id` = '{$_GET['product_id']}'");

			if (!$product) $this->showMessage('指定的商品不存在',AJAX?'0':'back');

			if (POST && AJAX) {
				$price = $_POST['price'];
				$num = $_POST['num'];

				if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$price)) {
					$this->outputJson(0,'价格格式错误');
				}
				if (!preg_match('/\d{1,100}/',$num)) {
					$this->outputJson(0,'数量必须为数字');
				}
				$_ENV['db']->runSql("UPDATE `product` ".$this->buildSql(array(
						'num' => $product['num'] + $num,
						'anum' => $product['bnum'],
						'aprice' => $product['bprice'],
						'bnum' => $num,
						'bprice' => $price
					))." WHERE `product_id` = '{$product['product_id']}'");
				$_ENV['db']->runSql("INSERT INTO `product_stock_history` ".$this->buildSql(array(
						'product_id' => $product['product_id'],
						'num' => $num,
						'price' => $price,
                        'uid' => $this->user['uid'],
                        'username' => $this->user['username'],
						'created_time' => $_ENV['time']
					)));
				$this->outputJson(1,'操作成功');
			}
			$this->view->history = $_ENV['db']->fetchAll("SELECT * FROM `product_stock_history` WHERE `product_id` = '{$product['product_id']}'");
			$this->showMainPage('admincp/order_stock_in');
		} else {
            $order_id = $_GET['order_id'];
            if (!$order_id) {
                $this->showMessage('请从待采购订单列表进入操作');
            }
            $pids = $_ENV['db']->fetchAll("SELECT p.* FROM `order_detail` as d LEFT JOIN `product` as p ON d.product_id=p.product_id WHERE d.order_id = '{$order_id}' AND d.product_num > p.num");
            $this->view->products = $pids;
			$this->showMainPage('admincp/order_stock_list');
		}
	}

    /**
     * 系统下单
     */
    public function systemsubmitModule() 
    {
        $step = in_array($_GET['step'],array(1,2,3,4,'view_cart')) ? $_GET['step'] : '1';
        if ($step != '1' && empty($_GET['uid']) && empty($_GET['lid'])) 
		{
            $this->showMessage('非法操作',-403);
        }

        /*[当前选择的客户]*/
        $currc = array();
        /*[当前选择的约货人]*/
        $currl = array();
        if($_GET['lid'])
        {
        	$lid = (int)$_GET['lid'];
        	$currl = customerEntity::GetUserRow($lid);
        	if (!$currl) $this->showMessage('指定的约货人不存在',-400);
            $this->view->$currl = $currl;
            $_GET['uid'] = $currl['customer_id'];
        }
        if ($_GET['uid']) 
        {
            $uid = (int)$_GET['uid'];
            $currc = customerEntity::GetRow($uid);
            if (!$currc) $this->showMessage('指定的客户不存在',-400);
            $this->view->currc = $currc;
        }
        
        switch ($step) 
        {
            case '1':  
				$this->view->addScript('rili');
            	//选择客户
                $customer = new customerControlPage();
				
				$where = ' 1=1 ';
				if($_GET['start_date'])
				{
					$where .= " and `created_time` >= '".AddDateTime($_GET["start_date"])."' ";
				}
				if($_GET['end_date'])
				{
					$where .= " and `created_time` <= '".AddDateTime($_GET["end_date"],23,59,59)."' ";
				}
				if($_GET['customer_name'])
				{
					$where .= " and `customer_name` like '%".$_GET["customer_name"]."%' ";
				}	
                $customer->CustomerList($where);
            break;
            case '2':
            	//选择约货人
				/*[已审核的约货人]*/
				$this->view->leaders = customerEntity::GetUserList($currc['customer_id'],'1');
			break;
            case '3':
            	//选择商品  
            	$data = $_GET;
                $data['step'] = 'view_cart';
                $data['ref'] = '3';
                $this->view->headlinks = '?'.http_build_query($data);
                $where = '1';
		        $page = (int)$_GET['page_no'];
		        $_GET['page_no'] = 'TPT';
				$products = $this->PrePage('product','product_id',$where,$page,'product_id asc');
				$cartinfo = @json_decode(cauthcode(cgetcookie('ccart')),1);
				if($cartinfo[$lid])
				{
					foreach((array)$products as $key=>$value)
					{
						$products[$key]['isCache'] = '0';
						if(array_key_exists($value['product_id'],$cartinfo[$lid]))
						{
							$products[$key]['isCache'] = '1';
						}
					}
				}
		        $this->view->products = $products;
            break;
            case '4':
            	
            	/*[ 购物车中的商品列表 ]*/
				$productarr = $this->GetProductByLid($currl['leader_id']);
            	
				$this->view->contract_number = "HT" . date('YmdHis');
            	
		        /*[ 计算应付价 ]*/
		        $pprice = 0;
		        foreach ((array)$productarr as $item) {
		        	$pprice += $item['sum']*$item['price'];
		        }
                
                // 合同类型列表
                $contract_list = explode("\n",$_ENV['config']['contract']);
                if (POST && AJAX) 
                {
                    $type = $_POST['type'];
                    if ('submitorder' == $type) 
                    {
                        // 数据验证
                        # 验证收货地址是否合法
                        $rid = (int)$_POST['rid'];
                        $cr = $_ENV['db']->fetch("SELECT * FROM `customer_receive` WHERE `cr_id` = '{$rid}'");
                        if (!$cr) $this->outputJson(0,'请选择收货地址');

                        # 验证发票信息是否合法
                        $fid = (int)$_POST['fid'];
                        $fapiao = $_ENV['db']->fetch("SELECT * FROM `fapiao` WHERE `uid` = '{$currc['customer_id']}' and fid = '{$fid}'");
                        if (!$fapiao) $this->outputJson(0,'请选择发票信息');

                        # 验证合同类型是否合法
                        $contract = $_POST['contract'];
                        if (!$contract || !in_array($contract,$contract_list)) $this->outputJson(0,'请选择正确的合同类型');
						$contract_number = $_POST['contract_number'];
						if (!$contract_number || mb_strlen($contract_number,'UTF-8') > 20) $this->outputJson(0,'合同号长度不能大于20');

                        # 验证下级处理人是否合法
                        $audit_member_id = (int)$_POST['audit_member_id'];
                        $audit_member = $_ENV['db']->fetch("SELECT m.uid,m.username,m.nickname FROM admincp_member as m LEFT JOIN admincp_member_perm as p ON m.uid=p.uid WHERE p.node_id = '{$_ENV['config']['orderrerid']}' AND m.uid='{$audit_member_id}'");
                        if (!$audit_member) $this->outputJson(0,'请选择订单复审人或您选择的复审人没有订单操作权限');

                        # 验证合同信息
                        $pc = $_POST['price_content'];// price_content
                        foreach ((array)$pc as $no=>$item) 
                        {
	                        $nt = strtr($no,array(1=>'预付款',2=>'收获后付款',3=>'尾款'));
							if(!ValidateDate($item['time']))
							{
				                $this->outputJson(0,"{$nt}付款时间格式错误");	
							}
							$pc[$no]['time'] = strtotime($item['time']);
							        
				            if (!ValidatePrice($item['price'])) 
							{
				           		 $this->outputJson(0,"{$nt}付款金额格式错误");
				            }
							if (!ValidatePrice($item['percent'])) 
							{
				                   $this->outputJson(0,"{$nt}付款百分比格式错误（请勿填入百分号）");
				            }
                        }
                        $pc = json_encode($pc);
                        // 数据验证结束

                       
                        /*购物车里的商品列表*/
						$products = $this->GetProductsByCar($productarr); 
                        
						/*[开启事务]*/
						$_ENV['db']->beginTransaction();
						
                        $osn = makeOrderId();
                        $sql = 'INSERT INTO `order` '.$this->buildSql(array(
                                'order_sn' => $osn,
                                'customer_id'   => $currc['customer_id'],
                                'customer_name' => $currc['customer_name'],
                                'address' => $cr['address'],
                                'tel' => $cr['tel'],
                                'zip' => $cr['zip'],
                                'username' => $cr['receive_name'],
                                'audit_state' => '2',
                                'price' => '0',
                                'created_time' => $_ENV['time'],
                                'last_time' => $_ENV['time'],
                                'pprice' => $pprice,
                                'fp_name' => $fapiao['name'],
                                'fp_tt' => $fapiao['tt'],
                                'fp_nr' => $fapiao['nr'],
                                'contract' => $contract,
								'contract_number' => $contract_number,
                                'co_member_id' => $audit_member_id,
                                'audit3_uid' => $audit_member_id,
                                'pc' => $pc,
								'leader_id'=>$currl['leader_id']
                            ));
                        $_ENV['db']->runSql($sql);
                        $oid = $_ENV['db']->insertId();
                        if (!$oid) 
                        {
                        	/*[回滚事务]*/
				 			$_ENV['db']->rollback();
                        	$this->outputJson(0,'系统异常，订单提交失败');
                        }
                        
                        
                    /*[新增订单明细]*/	
					$total_price = $total_pprice = 0;
		            foreach ((array)$products as $product) 
					{
		             	$cartproduct = $productarr[$product['product_id']];
						$price = $product['price']*$cartproduct['sum'];        //原价格
						$pprice = $cartproduct['sum']*$cartproduct['price'];   //实际价格
						$total_price += $price;
						$total_pprice += $pprice;
						$datas = array(
										'order_id' => $oid,
										'order_sn' => $osn,
										'product_name' => $product['name'],
										'product_id' => $product['product_id'],
										'product_price' =>$product['price'],
										'product_pprice' => $cartproduct['price'],
										'product_num' => $cartproduct['sum'],
										'product_total_price' =>$price,
										'product_total_pprice' =>  $pprice,
										'created_time' => $_ENV['time'],
										);
						$detailid = InsertTable('order_detail', $datas); 
						 
						if (!$detailid) 
						{
							 /*[回滚事务]*/
							 $_ENV['db']->rollback();
							 $this->outputJson(0,'系统异常，订单明细保存失败');
						}
		              }
                        
                        /*[更新订单价格历史记录]*/
						orderEntity::UpdatePrice(array('price' => $total_price,'pprice' => $total_pprice),$oid);
			            $this->addOrderHistory($osn,"后台下单并移交给{$audit_member['username']}[{$audit_member['nickname']}]审核");
					
						/*[提交事务]*/
						$_ENV['db']->commit();
						csetcookie('ccart','',-1);
						$this->outputJson(1,'操作成功');
                    } 
                    $this->outputJson(0,'非法操作');
                }
                // 读取收货地址列表
                $rlist = $_ENV['db']->fetchAll("SELECT * FROM `customer_receive` WHERE `customer_id` = '{$currc['customer_id']}'");
                $this->view->rlist = $rlist;
                // 读取发票列表
                $fapiaolist = $_ENV['db']->fetchAll("SELECT * FROM fapiao where uid = '{$currc['customer_id']}'");
                $this->view->fapiaolist = $fapiaolist;
                // 合同类型列表
                $this->view->contract_list = $contract_list;
                // 加载js
                $this->view->addScript('rili');
                // 下级受理人ID
                $this->view->member_list = $_ENV['db']->fetchAll('SELECT uid,username,nickname FROM `admincp_member` WHERE `uid` IN (SELECT `uid` FROM `admincp_member_perm` WHERE `node_id` = \''.(int)$_ENV['config']['orderrerid'].'\')');
                // 应付价
                $this->view->pprice = $pprice;
            break;

            case 'view_cart':
                $data = $_GET;
                $data['step'] = $data['ref'];
                unset($data['ref']);
                $this->view->headlinks = '?'.http_build_query($data);

                $cartinfo = @json_decode(cauthcode(cgetcookie('ccart')),1);
				$productarr = $cartinfo[$lid];
				
				if(!$productarr || count($productarr)==0)
				{
					$this->showMessage('购物车中无商品!','back');
				}
				
				/*[购物车里的商品]*/
				$products = $this->GetProductsByCar($productarr);
				
				$total_cost_price = $total_pra_price = 0;
				foreach ((array)$products as $k=>$product) 
				{
					$tempPid = $product['product_id'];
		        	$products[$k]['cost_price'] = $product['price']*$productarr[$tempPid]['sum'];                    //原价格小计
		            $products[$k]['pra_price']  = $productarr[$tempPid]['sum']*$productarr[$tempPid]['price'];      //实际价格小计
		            $total_cost_price += $products[$k]['cost_price'];     //原价格合计
		            $total_pra_price  += $products[$k]['pra_price'];      //实际价格合计
		         }
		        $this->view->total_cost_price = $total_cost_price;
		        $this->view->total_pra_price = $total_pra_price;
		        $this->view->products = $products;
				$this->view->productarr = $productarr;
				$this->view->leaderid = $lid;
            break;
        }
        $this->showMainPage('admincp/order/order_sb_'.$step);
    }

    
	/**
     * 弹出框（商品）
     */
    public function productModule()
	{
		$lid = $_REQUEST['lid'];
		if(!$lid)
		{
			$this->showMessage('指定的约货人不存在','back');
		}
		$pid = $_REQUEST['pid'];
		if(!$pid)
		{
			$this->showMessage('请选择商品!','back');
		}
		$cartinfo = @json_decode(cauthcode(cgetcookie('ccart')),1);
		$product = productEntity::GetRow($pid);
		$this->view->productName = $product['name'];    		//产品名称
		$this->view->productPrice = $product['price'];          //价格
		if($cartinfo && array_key_exists($lid,$cartinfo) && array_key_exists($pid,$cartinfo[$lid]))
		{
			if($cartinfo[$lid][$pid]['price'])
			{
				$this->view->productPrice = $cartinfo[$lid][$pid]['price']; 
			}
			$this->view->productSum = $cartinfo[$lid][$pid]['sum'];    	//购买数量
		}
		$this->view->lid = $lid;
		$this->view->pid = $pid;
		$this->showSmallPage('admincp/order/product');
	}
	/**
     * 将商品加入购物篮
     */
	public function addCarModule()
	{
		$lid = $_REQUEST['lid'];
		if(!$lid)
		{
			$this->outputJson(0,'指定的约货人不存在');
		}
		$pid = $_REQUEST['pid'];
		if(!$pid)
		{
			$this->outputJson(0,'请选择商品!');
		}	
		$price = $_REQUEST['productPrice'];
		/*[验证价格格式]*/
		if(!ValidatePrice($price)) $this->outputJson(0,'单价格式错误');
		
	     /*[验证商品是否存在]*/
         if (!productEntity::IsExists($pid)) $this->outputJson(0,'找不到指定的商品信息');
		 							
		$cartinfo = @json_decode(cauthcode(cgetcookie('ccart')),1);
		$cartinfo[$lid][$pid] = array(
									'price'=> (float)$price,
									'sum'=> (int)$_REQUEST['productSum']
									);
		csetcookie('ccart',cauthcode(json_encode($cartinfo),'ENCDOE'));
        $this->outputJson(1,'成功添加到购物车');
	}
    /**
     *  根据约货人获得购物车商品列表
     */
	private function GetProductByLid($lid)
	{
		 $cartinfo = @json_decode(cauthcode(cgetcookie('ccart')),1);
		 $productarr = $cartinfo[$lid];
		 if (!$productarr) 
		 {
			 if(AJAX)
			 {
				 $this->outputJson(0,'购物车中无商品!');
			 }
			 else
			 {
				 $this->showMessage('购物车中无商品!',AJAX?0:'back');
			 }
         }
		 return $productarr;
	}
	/**
     * 返回购物篮里商品列表
     */
	private function GetProductsByCar($productarr)
	{
		$pids = '';
        foreach ((array)$productarr as $pkey=>$pval) {$pids .= "{$pkey},";}
		$pids = rtrim($pids,',');
		/*[购物车里的商品]*/
		$products = productEntity::GetListByIDs($pids);
		return $products ;
	}

	/**
     * 从购物篮移除商品
     */
	public function moveCarModule()
	{
		$pid = $_REQUEST['pid'];
		$lid = $_REQUEST['lid'];
		$cartinfo = @json_decode(cauthcode(cgetcookie('ccart')),1);
		unset($cartinfo[$lid][$pid]);
        csetcookie('ccart',cauthcode(json_encode($cartinfo),'ENCDOE'));
        $this->outputJson(1,'移除成功!');
	}
	/**
     * 添加收货地址
     */
	public function addAddressModule()
	{ 
		$lid = $_REQUEST['lid'];
		/*[约货人信息]*/
		$leader = customerEntity::GetLeaderRow($lid);
		if (!$leader) $this->outputJson(0,'指定的约货人不存在','zip');
		$customer = customerEntity::GetRow($leader['customer_id']);
		if (!$customer) $this->outputJson(0,'指定的客户不存在','zip');
		
		$tempdata = getRequests(array('address','zip','tel','receive_name'));
		if (!preg_match('/^\d{6}$/',$tempdata['zip'])) 
		{
			$this->outputJson(0,'邮政编码必须为6位数字','zip');
		}
        if (!preg_match('/^(\d{7}|\d{11})$/',$tempdata['tel'])) 
		{
            $this->outputJson(0,'联系电话必须为7或11位数字','tel');
        }
        if (!$tempdata['address'] || !$tempdata['receive_name']) 
		{
             $this->outputJson(0,'请补全信息');
        }
		$tempdata['customer_id'] = $customer['customer_id'];
		$rnewid = InsertTable('customer_receive', $tempdata); 
		if($rnewid)
		{
             $this->outputJson(1,"<li><input type='radio' value='{$rnewid}' name='rid' id='r{$rnewid}'/><label for='r{$rnewid}'>{$tempdata['address']}&nbsp;&nbsp;{$tempdata['receive_name']}&nbsp;&nbsp;{$tempdata['zip']}&nbsp;&nbsp;{$tempdata['tel']}</label></li>");
		}
		else
		{
			$this->outputJson(0,'非法操作');
		}
	}

    /**
     * 订单查看
     */
    public function viewOrderModule() {
        $order_id = (int)$_GET['order_id'];

        $order_detail = $_ENV['db']->fetch("SELECT * FROM `order` WHERE `order_id` = '{$_GET['order_id']}'");
        $order_products = $_ENV['db']->fetchAll("SELECT * FROM `order_detail` WHERE `order_id` = '{$order_id}'");
        $order_history = $_ENV['db']->fetchAll("SELECT * FROM `order_history` WHERE `order_id` = '{$order_id}'");

        $this->view->order_products = $order_products;
        $this->showMainPage('admincp/order_view');
    }

    /**
     * 订单打印模版设置
     */
    public function print_templateModule() {
		$this->view->addScript('LodopFuncs');
        if(POST && AJAX) {
            $type = $_POST['type'];

            if ('add' == $type) {
                $data = getRequests(array('name','content'));
                
                if(empty($data['name']) || empty($data['content'])){
                    $this->outputJson(0,'请补全信息');
                }

                $_ENV['db']->runSql("INSERT INTO `print_template` (`name`,`content`) VALUES ('{$data['name']}','{$data['content']}')");
                $this->outputJson(1,'操作成功');
            } elseif('fast_edit' == $type) {
                $id = (int)$_POST['wparam'];
                $field = $_POST['field'];
                $val = $_POST['val'];

                $_ENV['db']->runSql("UPDATE `print_template` SET `{$field}` = '{$val}' WHERE `pid` = '{$id}'");
                $this->outputJson(1,'操作成功');
            } elseif('delete' == $type) {
                $id = (int)$_POST['id'];
                $_ENV['db']->runSql("DELETE FROM `print_template` WHERE `pid` = '{$id}'");
                $this->outputJson(1,'操作成功');
            }

            $this->outputJson(-403,'非法操作');
        }

        $this->view->templates = $_ENV['db']->fetchAll("SELECT * FROM `print_template` ORDER BY `pid` DESC");
        $this->showMainPage('admincp/order_template');
    }

    /**
     * 获取订单列表
     */
    private function getOrderList($state='',$userid='') {
        $where = ' where 1 ';

        if ($state!='' && $userid!='') {
            switch ($state) {
                case 'fenpei':
                    $id = '0';
                break;

                case 'yewuyuan':
                    $id = '1';
                break;

                case 'shenpi':
                    $id = '2';
                break;

                case 'kucun':
                    $id = '3';
                break;

                case 'caigou':
                    $id = '4';
                break;

                case 'caiwu':
                    $id = '2,3,4,5';
                break;
            }

            $where .= " and audit_state IN ({$id}) ";
            
            //如果指定了用户但是当前用户为超级管理员就不受限制 , 且$state是caiwu 因为所有账户都能看到所有财务订单 update by txz
            if (!in_array($this->user['uid'],$_ENV['config']['superadmin']) && $state!='caiwu') {
                $where .= " and co_member_id = '{$userid}' ";
            }
        }

        if ($_GET['searchtype']) {
            switch($_GET['searchtype']) {
                case 'sn':
                    $where .= " and order_sn = '{$_GET['keyword']}'";
                break;

                case 'my':
                    if ($state == 7) {
                    } else {
                        $where .= " and audit".($state+1)."_uid = '{$this->user['uid']}'";
                    }
                break;
            }
        }

        if ($_GET['osc'] && $_GET['ost']) {
            $order = "order by `{$_GET['osc']}` {$_GET['ost']}";
        } else {
            $order = 'order by `order_id` desc';
        }


        $rowset = $_ENV['db']->fetch("SELECT count(order_id) as `total` FROM `order` {$where}");
        $total = $rowset['total'];
        unset($rowset);

        $pager = new class_pager();
        $pager->setConfig((int)$_GET['page_no'],$total);
        $_GET['page_no'] = 'TPT';
        $pager->setUrl("?".http_build_query($_GET),'TPT');

        $this->view->pager = $pager->output();
        $this->view->orders = $_ENV['db']->fetchAll("SELECT * FROM `order` {$where} {$order} LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
    }

    /**
     * 添加订单操作记录
     */
    private function addOrderHistory($osn,$message,$mark='') {        
        $_ENV['db']->runSql("INSERT INTO `order_history` ".$this->buildSql(array(
                'order_sn' => $osn,
                'username' => $this->user['nickname'],
                'desc' => $message,
                'mark' => $mark,
                'timestamp' => $_ENV['time'],
            )));
    }
	
	
	/*[订单统计]*/
	public function summaryModule()
	{
		$this->view->addScript('rili');
		$this->view->addScript('autocomplete');
		$customer  = $_GET['searchCustomer'];
		$sel_UName = $_GET['searchUser'];
		
		$wherearr = $this->GetSummaryWhere();
		$summarylist = orderEntity::GetOrderSummary($wherearr);
		$orderlist = orderEntity::GetOrders($wherearr);
		
		 if($_GET['btn']=='导出')
		{
			$str = '';
 
$str .= '
		<table border="2">
       	<tr>
            <th>客户</th>
            <th>订单总数量</th>
            <th>订单总额度(成本)</th>
            <th>订单总额度(实际)</th>
            <th>已付款</th>
            <th>欠款</th>
            <th>订单信息</th>
       </tr>';
	   
	    foreach((array)$summarylist as $summary)
		{
			$str .= "<tr>
						<td>{$summary['customer_name']}</td>
						<td>{$summary['countorder']}</td>
						<td>{$summary['total_price']}</td>
						<td>{$summary['total_pprice']}</td>
						<td>{$summary['pays']}</td>
						<td>{$summary['qians']}</td>
						<td>
						   <table border='1'>
						   	<tr>
								<th>订单号</th>
								<th>下单时间</th>
								<th>订单状态</th>
								<th>总额度(成本)</th>
								<th>总额度(实际)</th>
								<th>已付款</th>
								<th>欠款</th>
						   </tr>";
						   
						  foreach((array)$orderlist as $order)
						  {
                    		if($summary['customer_id']==$order['customer_id'])
							{
								$str .= "<tr>
									<td>".$order['order_sn']."</td>
									<td>".($order['created_time'] ? date('Y-m-d H:i',$order['created_time']) : '-')."</td>
									<td>".$order['audit_state']."</td>
									<td>".$order['totoal_price']."</td>
									<td>".$order['total_ppirce']."</td>
									<td>".$order['payed']."</td>
									<td>".$order['qian']."</td>
								</tr>";
							}
						  }
						  $str .= '</table>
						</td>
					 <tr>';
		}
		$str .= '</table>';

			//转换为GBK编码
			$str = iconv("UTF-8","GBK",$str);
			 
			//输出
			header('Content-Length: '.strlen($str));
			header("Content-type:application/vnd.ms-excel");
			header("Content-Disposition:filename={$name}.xls");
			echo $str;
		}
		else 
		{
			$this->view->summarylist = $summarylist;
			$this->view->orderlist = $orderlist;
			///print_r($this->view->summarylist);
			//print_r($this->view->orderlist);
			
			$this->view->customer = $customer;
			$this->view->sel_UName = $sel_UName;
			$this->showMainPage('admincp/order/order_summary');
		}
	}
	
	private function GetSummaryWhere()
	{
		$wheres = array();
		$where = ' 1=1 ' ;
		if($_GET['start_date'])
		{
			$where .= " and o.`createdate` >= '".AddDateTime($_GET["start_date"])."' ";
		}
		if($_GET['end_date'])
		{
			$where .= " and o.`createdate` <= '".AddDateTime($_GET["end_date"],23,59,59)."' ";
		}
		if($_GET['searchCustomer'])
		{
			$where .= " and o.`customer_id` = ".$_GET["searchCustomer"]." ";
		}
		if($_GET['searchUser'])
		{
			$where .= " and o.`co_member_id` = ".$_GET["searchUser"]." ";
		}
		if($_GET['status'] && $_GET['status'] !='0')
		{
			$where .= " and o.`audit_state` = '".$_GET["status"]."' ";
		}
		if($_GET['orderno'])
		{
			$where .= " and o.order_sn like '%".strtolower( $_GET["orderno"])."%' ";
		}
		$wheres[0] = $where ;
		$where1 = ' 1=1 ' ;
		if($_GET['product'])
		{
			$where1 .= " `product_name` like '%".$_GET["product"]."%' ";
		}
		$wheres[1] = $where1 ;
		return $wheres;
	}
	
}